package com.xiaochi.subject.common.context;


import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 *
 * 登录上下文对象
 * @author zqx
 * @since 2024/9/4
 */
public class LoginContextHolder {

    //这里有三种 threadLocal

    //这个ThreadLocal 在上下文时，会遇到传递不下去的问题
//    private static final ThreadLocal<Map<String , Object>> THREAD_LOCAL =
//            new ThreadLocal<>();

    //这个InherItableThreadLocal 虽然是可以传递上下文，但是遇到线程池复用的时候就不行了
    // todo 9/6今天知道了上下文传递在线程池复用什么意思了  就像ThreadPoolTaskExecutor中的使用装饰器一样
    private static final InheritableThreadLocal<Map<String , Object>> THREAD_LOCAD =
            new InheritableThreadLocal<>();

    //这里是有一个阿里的ThreadLocal
    // todo 9/6这个就是阿里的ttl 可以解决上面那几个问题
//    private static final TransmitThreadLocal<Map<String,Object>> THREAD_LOCAL =
//            new TransmitThreadLocal<>();


    public static void setThreadLocal(String key,Object value){
        Map<String, Object> threadLocalMap = getThreadLocalMap();
        threadLocalMap.put(key,value);
    }

    public static Object getThreadLocal(String key){
        Map<String, Object> threadLocalMap = getThreadLocalMap();
        return threadLocalMap.get(key);
    }

    public static String getLoginId(){
        return (String) getThreadLocalMap().get("loginId");
    }

    public static void remove(){
        THREAD_LOCAD.remove();
    }

    public static Map<String ,Object> getThreadLocalMap(){
        Map<String, Object> map = THREAD_LOCAD.get();
        if (Objects.isNull(map)){
            map = new ConcurrentHashMap<>();
            THREAD_LOCAD.set(map);
        }
        return map;
    }

}
